package com.wz.leetcode.stackandqueue;

import java.util.Deque;
import java.util.LinkedList;

public class BasicCalculator_224 {
    /**
     * 核心本质是，将符号位直接乘进去了，就相当于去掉了括号，计算每一项
     * 这里每一层括号都对应栈里面的一层。栈顶对应当前处理层级的符号
     * @param s
     * @return
     */
    public static int calculate(String s) {
        Deque<Integer> ops = new LinkedList<>();
        ops.push(1);
        int sign = 1;

        int ret = 0;
        int n = s.length();
        int i = 0;

        while (i < n) {
            if (s.charAt(i) == ' ') {
                i++;
            } else if (s.charAt(i) == '+') {
                sign = ops.peek();
                i++;
            } else if (s.charAt(i) == '-') {
                sign = -ops.peek();
                i++;
            } else if (s.charAt(i) == '(') {
                ops.push(sign);
                i++;
            } else if (s.charAt(i) == ')') {
                ops.pop();
                i++;
            } else {
                long num = 0;
                while (i < n && Character.isDigit(s.charAt(i))) {
                    num = num * 10 + (s.charAt(i) - '0');
                    i++;
                }
                ret += sign * num;
            }
            System.out.println("sign: " + sign);
            System.out.println("ops: " + ops);
            System.out.println("ret: " + ret);
            System.out.println();
        }
        return ret;
    }

    public static void main(String[] args) {
        System.out.println(calculate("1 - (4 - 2) + 3"));
    }
}
